package com.anrongtec.zcpt.service;

import com.ansec.mdm.GetLocationInfoIntecface;
import com.ansec.mdm.ILocationListener;
import com.ansec.mdm.ILocationService;
import com.art.base.util.log.LogUtil;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class GetLocationInfoService extends Service{
	// 是否连接了MDM location 定位
	private boolean isLocationConn;
	protected ILocationService locationService;

	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		bindLocationService();
		LogUtil.trace(Log.DEBUG, "test", "conn service onCreate");
	}
	
	@Override
	public void onRebind(Intent intent) {
		super.onRebind(intent);
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	/**
	 * 绑定定位服务
	 */
	private boolean bindLocationService() {
		Intent intent = new Intent("com.ansec.mdm.Action.BindLocation");
		intent.setPackage("com.ansec.mdm");
		return bindService(intent, locationConn, Context.BIND_AUTO_CREATE);
	}

	@Override
	public void onDestroy() {
		unbindService(locationConn);
		super.onDestroy();
	}

	/**
	 * 定位conn
	 */
	private ServiceConnection locationConn = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			locationService = ILocationService.Stub.asInterface(service);
			try {
				locationService.start(0, new ILocationListener.Stub() {
					
					@Override
					public void onChange(String location) throws RemoteException {
						LogUtil.trace(Log.DEBUG, "test", location+"123");
					}
				});
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			isLocationConn = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			locationService = null;
		}
	};

	/**
	 * 向外提供的binder
	 */
	GetLocationInfoIntecface.Stub binder = new GetLocationInfoIntecface.Stub() {

		@Override
		public void onLocation(int type, ILocationListener listener) throws RemoteException {
			// 如果确定locationService已经连接成功
			if (!isLocationConn && locationService == null) {
				listener.onChange("绑定定位服务失败");
				return;
			}
			locationService.start(type, listener);
		}
	};

}
